<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.username" placeholder="用户名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getUsers">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="users"  border highlight-current-row v-loading="listLoading"  style="width: 100%;">
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="username" label="用户名" width="80" >
			</el-table-column>
			<el-table-column prop="nickname" label="姓名" width="80" >
			</el-table-column>
			<el-table-column prop="departmentid" label="部门" width="80" :formatter="formatDepartment">
			</el-table-column>

			<el-table-column prop="gender" label="性别" width="80" :formatter="formatGender">
			</el-table-column>

			<el-table-column prop="age" label="年龄" width="80" >
			</el-table-column>

			<el-table-column  label="头像" width="100px" >
				<template  scope="scope">
					<img v-show="scope.row.headportrait.length>0" :src="scope.row.headportrait" style="width: 100px;height: 100px;padding: 0px;margin: 0px"/>
				</template>

			</el-table-column>

			<el-table-column prop="birth" label="生日" width="100" :formatter="formatBirth">
			</el-table-column>
			<el-table-column prop="address" label="居住地址" width="100" >
			</el-table-column>
			<el-table-column prop="email" label="邮箱" width="80" >
			</el-table-column>
			<el-table-column prop="telephone" label="电话" width="80" >
			</el-table-column>
			<el-table-column prop="duty" label="职务" width="80" >
			</el-table-column>
			<el-table-column prop="handfreetelephone" label="分机号" width="80" >
			</el-table-column>
			<el-table-column prop="qq" label="QQ号" width="80" >
			</el-table-column>
			<el-table-column prop="weixin" label="微信号" width="80" >
			</el-table-column>
			<el-table-column prop="dutystatus" label="在职状态" width="80" :formatter="formatDutystatus" >
			</el-table-column>


			<el-table-column prop="loginstate" label="登录状态" width="80" :formatter="formatLoginstate">
			</el-table-column>
			<el-table-column prop="role" label="角色" width="80" :formatter="formatRole">
			</el-table-column>
			<el-table-column prop="createtime" label="注册时间" width="100"  :formatter="formatCreatetime">
			</el-table-column>


			<el-table-column label="操作" min-width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<!--<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>-->
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog title="编辑" v-model="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="用户名:" prop="username" >
					<el-input v-model="editForm.username" auto-complete="off" disabled="true"></el-input>
				</el-form-item>

				<el-form-item label="姓名:" prop="nickname">
					<el-input v-model="editForm.nickname" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="部门:" prop="departmentid">
					<el-select v-model="editForm.departmentid" placeholder="请选择部门">
						<el-option v-for="item in this.departments"
								   :label="item.depname"
								   :value="item._id">
						</el-option>

					</el-select>
				</el-form-item>


				<el-form-item label="性别:" prop="gender">
					<el-radio-group v-model="editForm.gender">
						<el-radio class="radio" :label="0">男</el-radio>
						<el-radio class="radio" :label="1">女</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="年龄:" prop="age">
					<el-input-number v-model="editForm.age"  :min="1" :max="150" label="描述文字"></el-input-number>
				</el-form-item>

				<el-form-item label="头像:" prop="headportrait">
					<el-upload class="avatar-uploader"
							   action=""
							   :http-request="upload"
							   :show-file-list="false"
							   :on-change="handlePictureCardPreview"
							   :before-upload="beforeAvatarUpload">
						<img v-if="imageUrl" :src="imageUrl" class="avatar">
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>

				<el-form-item label="生日:" prop="birth">
					<el-date-picker
							v-model="editForm.birth"
							type="date"
							placeholder="选择日期">
					</el-date-picker>
				</el-form-item>

				<el-form-item label="居住地址:" prop="address">
					<el-input v-model="editForm.address" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="邮箱:" prop="email">
					<el-input v-model="editForm.email" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="电话:" prop="telephone">
					<el-input v-model="editForm.telephone" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="职务:" prop="duty">
					<el-input v-model="editForm.duty" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="在职状态:">
					<el-radio-group v-model="editForm.dutystatus">
						<el-radio class="radio" :label="0">在职</el-radio>
						<el-radio class="radio" :label="1">离职</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="分机号:" prop="handfreetelephone">
					<el-input v-model="editForm.handfreetelephone" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="QQ号:" prop="qq">
					<el-input v-model="editForm.qq" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="微信号:" prop="weixin">
					<el-input v-model="editForm.weixin" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="登录状态:">
					<el-radio-group v-model="editForm.loginstate">
						<el-radio class="radio" :label="0">允许登录</el-radio>
						<el-radio class="radio" :label="1">禁止登录</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="角色:">
					<el-select v-model="editForm.role" placeholder="请选择用户角色">
						<el-option label="超级管理员" value=0></el-option>
						<el-option label="管理员" value=1></el-option>
						<el-option label="普通用户" value=2></el-option>
						<el-option label="销售" value=3></el-option>
						<el-option label="库管" value=4></el-option>
					</el-select>
				</el-form-item>

				<p style="float: left;color: red">注：创建用户默认密码123456，后期密码可修改</p>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>


		<!--新增界面-->
		<el-dialog title="新增" v-model="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="用户名:" prop="username">
					<el-input v-model="addForm.username" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="姓名:" prop="nickname">
					<el-input v-model="addForm.nickname" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="部门:" prop="departmentid">
					<el-select v-model="addForm.departmentid" placeholder="请选择部门">
						<el-option v-for="item in this.departments"
						:label="item.depname"
						:value="item._id">
						</el-option>

					</el-select>
				</el-form-item>


				<el-form-item label="性别:" prop="gender">
					<el-radio-group v-model="addForm.gender">
						<el-radio class="radio" :label="0">男</el-radio>
						<el-radio class="radio" :label="1">女</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="年龄:" prop="age">
					<el-input-number v-model="addForm.age"  :min="1" :max="150" label="描述文字"></el-input-number>
				</el-form-item>

				<el-form-item label="头像:" prop="headportrait">
					<!--<label>头像:</label> <input  style="float: left;width: 300px;height:80px;" id="upfile" type="file">-->

					<el-upload class="avatar-uploader"
							   action="123"
							   :show-file-list="false"
							   :on-change="handlePictureCardPreview"
							   :before-upload="beforeAvatarUpload">
						<img v-if="imageUrl" :src="imageUrl" class="avatar">
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>

				</el-form-item>

				<el-form-item label="生日:" prop="birth">
					<el-date-picker
							v-model="addForm.birth"
							type="date"
							placeholder="选择日期">
					</el-date-picker>
				</el-form-item>

				<el-form-item label="居住地址:" prop="address">
					<el-input v-model="addForm.address" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="邮箱:" prop="email">
					<el-input v-model="addForm.email" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="电话:" prop="telephone">
				<el-input v-model="addForm.telephone" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="职务:" prop="duty">
					<el-input v-model="addForm.duty" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="在职状态:">
					<el-radio-group v-model="addForm.dutystatus">
						<el-radio class="radio" :label="0">在职</el-radio>
						<el-radio class="radio" :label="1">离职</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="分机号:" prop="handfreetelephone">
					<el-input v-model="addForm.handfreetelephone" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="QQ号:" prop="qq">
					<el-input v-model="addForm.qq" auto-complete="off"></el-input>
				</el-form-item>

				<el-form-item label="微信号:" prop="weixin">
					<el-input v-model="addForm.weixin" auto-complete="off"></el-input>
				</el-form-item>




				<el-form-item label="登录状态:">
					<el-radio-group v-model="addForm.loginstate">
						<el-radio class="radio" :label="0">允许登录</el-radio>
						<el-radio class="radio" :label="1">禁止登录</el-radio>
					</el-radio-group>
				</el-form-item>



				<el-form-item label="角色:">
					<el-select v-model="addForm.role" placeholder="请选择用户角色">

						<!--<el-option v-for="item in this.departments"-->
								   <!--:label="item.depname"-->
								   <!--:value="item._id">-->
						<!--</el-option>-->


						<el-option label="超级管理员" value=0></el-option>
						<el-option label="管理员" value=1></el-option>
						<el-option label="普通用户" value=2></el-option>
						<el-option label="销售" value=3></el-option>
						<el-option label="库管" value=4></el-option>
					</el-select>
				</el-form-item>

				<p style="float: left;color: red">注：创建用户默认密码123456，后期密码可修改</p>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>




	</section>
</template>

<script>
    import util from '../../common/js/util'
    //import NProgress from 'nprogress'
    import { getUserList, removeUser, editUser, addUser ,getAllDepartmentList} from '../../api/api';
    import ElFormItem from "../../../node_modules/element-ui/packages/form/src/form-item.vue";
    import ElButton from "../../../node_modules/element-ui/packages/button/src/button.vue";
    import ElRow from "element-ui/packages/row/src/row";
    import ElCol from "element-ui/packages/col/src/col";

    export default {
        components: {
            ElCol,
            ElRow,
            ElButton,
            ElFormItem},
        data() {
            return {
                baseImageUrl:util.getUploadImageBaseUrl(),
                imageUrl: '',
				uploadfile:'',
                filters: {
                    username: ''
                },
                users: [],
				departments:[],
                total: 0,
                page: 1,
                listLoading: false,
                sels: [],//列表选中列
                editFormVisible: false,//编辑界面是否显示
                editLoading: false,
                editFormRules: {
                    username: [
                        { required: true, message: '请输入用户名', trigger: 'blur' }
                    ]
                },
                //编辑界面数据
                editForm: {
                    id: 0,
                    username: '',
                    nickname:'',
                    gender:'',
                    age:'',
                    birth:'',
                    address:'',
                    email:'',
                    departmentid:'',
                    telephone:'',
                    duty:'',
                    handfreetelephone:'',
                    qq:'',
                    weixin:'',
                    dutystatus:'',
                    headportrait:'',
                    loginstate: 0,
                    role: 2
                },

                addFormVisible: false,//新增界面是否显示
                addLoading: false,
                addFormRules: {
                    username: [
                        { required: true, message: '请输入用户名', trigger: 'blur' }
                    ]
                },
                //新增界面数据
                addForm: {
                    username: '',
                    nickname:'',
                    gender:'',
                    age:'',
                    birth:'',
                    address:'',
                    email:'',
                    departmentid:'',
                    telephone:'',
                    duty:'',
                    handfreetelephone:'',
                    qq:'',
                    weixin:'',
                    dutystatus:'',
                    headportrait:'',
                    loginstate: 0,
                    role: 2
                }

            }
        },
        methods: {
            handlePictureCardPreview(file, fileList) {
                this.imageUrl = file.url;

            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isPNG = file.type === 'image/png';

                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG&&!isPNG) {
                    this.$message.error('上传头像图片只能是 JPG或PNG 格式!');
                }

                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                if((isPNG || isJPG) && isLt2M){
                    this.uploadfile = file;
                }

                return (isPNG || isJPG) && isLt2M;
            },
            //用户性别转换
            formatGender: function (row,colimn) {
                if(row.gender == '0'){
                    return '男';
                }
                else if(row.gender == '1'){
                    return '女';
                }
                else {
                    return '未知';
                }
            },

            //用户部门转换
            formatDepartment: function (row,colimn) {

                for (var i=0;i<this.departments.length;i++){
                    var dep = this.departments[i];
                    if(dep._id == row.departmentid){
                        return dep.depname;
					}
					break;
				}
				return '';
            },


            //登录显示转换
            formatLoginstate: function (row, column) {

                if(row.loginstate == '0'){
                    return '允许登录';
                }
                else if(row.loginstate == '1'){
                    return '禁止登录';
                }
                else {
                    return '未知';
                }
            },



            formatDutystatus: function (row, column) {

                if(row.dutystatus == '0'){
                    return '在职';
                }
                else if(row.dutystatus == '1'){
                    return '离职';
                }
                else {
                    return '未知';
                }
            },

            //角色显示转换
            formatRole: function (row, column) {
                if(row.role == '0'){
                    return '超级管理员';
				}
                else if(row.role == '1'){
                    return '管理员';
                }
				else if(row.role == '2'){
                    return '普通用户';
                }
                else if(row.role == '3'){
                    return '销售';
                }
                else if(row.role == '4'){
                    return '库管';
                }
                else {
                    return '未知';
                }

            },

            formatCreatetime: function (row,column) {
               return util.formatDate.format(new Date(row.createtime), 'yyyy-MM-dd hh:mm:ss')
            },
            formatBirth: function (row,column) {
                return util.formatDate.format(new Date(row.createtime), 'yyyy-MM-dd')
            },

            handleCurrentChange(val) {
                this.page = val;
                this.getUsers();
            },
            //获取用户列表
            getUsers() {
                let para = {
                    page: this.page,
					rows:10,
                    username: this.filters.username
                };
                this.listLoading = true;
                //NProgress.start();
                getUserList(para).then((res) => {
                    this.total = res.sumpage;
                    this.users = res.data;
                    this.listLoading = false;
                    //NProgress.done();
                });
            },


			getDepartmentsAllList(){
                getAllDepartmentList().then((res) => {
                    var count = res.sumpage;
                    this.departments = res.data;
                    //NProgress.done();
                });
			},

            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    let para = { ids: row._id };
                    removeUser(para).then((res) => {
                        this.listLoading = false;
                        let {status,msg} = res;
                        if(status == 0){
                            //NProgress.done();
                            this.$message({
                                message: msg,
                                type: 'error'
                            });
                        }
                        else {
                            //NProgress.done();
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            this.getUsers();
                        }

                    });
                }).catch(() => {

                });
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.editFormVisible = true;
                this.editForm = {
                    id: row._id,
                    username: row.username,
                    nickname:row.nickname,
                    gender:parseInt(row.gender),
                    age:row.age,
                    birth:row.birth,
                    address:row.address,
                    email:row.email,
                    departmentid:row.departmentid,
                    telephone:row.telephone,
                    duty:row.duty,
                    handfreetelephone:row.handfreetelephone,
                    qq:row.qq,
                    weixin:row.weixin,
                    dutystatus:parseInt(row.dutystatus),
                    headportrait:row.headportrait,
                    loginstate: parseInt(row.loginstate),
                    role:row.role
                };
            },
            //显示新增界面
            handleAdd: function () {
                this.addFormVisible = true;
                this.addForm = {
                    username: '',
                    loginstate: 0,
                    gender: 0,
                    dutystatus: 0,
                    role: '2'
                };
            },
            //编辑
            editSubmit: function () {
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.editLoading = true;
                            //NProgress.start();
                            let para = Object.assign({}, this.editForm);
                            para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');

                            var formdata1=new FormData();// 创建form对象
                            formdata1.append('id',para.id);
                            formdata1.append('username',para.username);
                            formdata1.append('loginstate',para.loginstate);
                            formdata1.append('role',para.role);
                            if(this.uploadfile){
                                formdata1.append('avatar',this.uploadfile);// 通过append向form对象添加数据,可以通过append继续添加数据
                            }
                            formdata1.append('nickname',para.nickname);
                            formdata1.append('gender',para.gender);
                            formdata1.append('age',para.age);
                            formdata1.append('birth',para.birth);
                            formdata1.append('address',para.address);
                            formdata1.append('email',para.email);
                            formdata1.append('departmentid',para.departmentid);
                            formdata1.append('telephone',para.telephone);
                            formdata1.append('duty',para.duty);
                            formdata1.append('handfreetelephone',para.handfreetelephone);
                            formdata1.append('qq',para.qq);
                            formdata1.append('weixin',para.weixin);
                            formdata1.append('dutystatus',para.dutystatus);

                            editUser(formdata1).then((res) => {
                                this.editLoading = false;
                                let {status,msg} = res;
                                if(status == 0){
                                    //NProgress.done();
                                    this.$message({
                                        message: msg,
                                        type: 'error'
                                    });
                                }
                                else {
                                    //NProgress.done();
                                    this.$message({
                                        message: '提交成功',
                                        type: 'success'
                                    });
                                    this.$refs['editForm'].resetFields();
                                    this.editFormVisible = false;
                                    this.getUsers();
                                }

                            });
                        });
                    }
                });
            },

            //新增
            addSubmit: function () {
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.addLoading = true;
                            //NProgress.start();
                            let para = Object.assign({}, this.addForm);
                            para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');

                            var formdata1=new FormData();// 创建form对象
                            formdata1.append('username',para.username);
                            formdata1.append('loginstate',para.loginstate);
                            formdata1.append('role',para.role);

                            if(this.uploadfile){
                           		formdata1.append('avatar',this.uploadfile);// 通过append向form对象添加数据,可以通过append继续添加数据
                            }

                            formdata1.append('nickname',para.nickname);
                            formdata1.append('gender',para.gender);
                            formdata1.append('age',para.age);
                            formdata1.append('birth',para.birth);
                            formdata1.append('address',para.address);
                            formdata1.append('email',para.email);
                            formdata1.append('departmentid',para.departmentid);
                            formdata1.append('telephone',para.telephone);
                            formdata1.append('duty',para.duty);
                            formdata1.append('handfreetelephone',para.handfreetelephone);
                            formdata1.append('qq',para.qq);
                            formdata1.append('weixin',para.weixin);
                            formdata1.append('dutystatus',para.dutystatus);

                            addUser(formdata1).then((res) => {
                                let {status,msg} = res;
                                this.addLoading = false;

                                if(status == 0){
                                    //NProgress.done();
                                    this.$message({
                                        message: msg,
                                        type: 'error'
                                    });
                                }
                                else {
                                    //NProgress.done();
                                    this.$message({
                                        message: msg,
                                        type: 'success'
                                    });
                                    this.$refs['addForm'].resetFields();
                                    this.addFormVisible = false;
                                    this.getUsers();
                                }
                            });
                        });
                    }
                });
            }
        },
        mounted() {
            this.getUsers();
            this.getDepartmentsAllList();
        }
    }

</script>

<style scoped>
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}
	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}
	.avatar-uploader-icon {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}
	.avatar {

		width: 178px;
		height: 178px;
		display: block;
	}
</style>